package com.jinlia.show.modules.base.service;

import com.alibaba.fastjson.JSONObject;
import com.jinlia.show.common.core.exception.MyRuntimeException;
import com.jinlia.show.modules.base.constant.DeliveryStatusEnum;
import com.jinlia.show.modules.base.constant.DeliveryTypeEnum;
import com.jinlia.show.modules.base.constant.ErrandOrderStatusEnum;
import com.jinlia.show.modules.base.constant.MgsTempEnum;
import com.jinlia.show.modules.base.constant.i.IBaseEnum;
import com.jinlia.show.modules.base.system.entity.DeliveryOrder;
import com.jinlia.show.modules.base.system.entity.ErrandOrder;
import com.jinlia.show.modules.base.system.entity.Order;
import com.jinlia.show.modules.base.system.service.DeliveryOrderMapperService;
import com.jinlia.show.modules.base.system.service.ErrandOrderMapperService;
import com.jinlia.show.modules.base.system.service.OrderMapperService;
import com.jinlia.show.modules.base.wxapp.entity.AccessToken;
import com.jinlia.show.modules.base.wxapp.entity.AppConfig;
import com.jinlia.show.modules.base.wxapp.entity.MsgTemp;
import com.jinlia.show.modules.base.wxapp.entity.User;
import com.jinlia.show.modules.base.wxapp.service.AccessTokenMapperService;
import com.jinlia.show.modules.base.wxapp.service.AppConfigMapperService;
import com.jinlia.show.modules.base.wxapp.service.MsgTempMapperService;
import com.jinlia.show.modules.base.wxapp.service.UserMapperService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 微信消息订阅器
 */
@Slf4j
@Service
public class WxMessageService {

    //订阅消息地址
    public String messageSubscribeApi = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%s";
    @Autowired
    private RestTemplate wxRestTemplate;
    @Autowired
    private AccessTokenMapperService accessTokenMapperService;
    @Autowired
    private OrderMapperService orderMapperService;
    @Autowired
    private DeliveryOrderMapperService deliveryOrderMapperService;
    @Autowired
    private UserMapperService userMapperService;
    @Autowired
    private MsgTempMapperService msgTempMapperService;
    @Autowired
    private AppConfigMapperService appConfigMapperService;
    @Autowired
    private ErrandOrderMapperService errandOrderMapperService;

    /**
     * @param orderId
     * @return
     */
    public String sendConfirmOrderMsg(Long orderId,String wxVersion) {
        Order byIdSaleOrder = orderMapperService.getById(orderId);
        User byIdUser = userMapperService.getById(byIdSaleOrder.getUserId());
        MsgTemp one = msgTempMapperService.lambdaQuery()
                .eq(MsgTemp::getAppId, byIdSaleOrder.getAppId())
                .eq(MsgTemp::getTemplateType, MgsTempEnum.confirm_order.getValue())
                .one();
        //发送预约通知
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("character_string1", singleJsonObject("value", byIdSaleOrder.getOrderNum()));//订单编号
        jsonObject.put("thing3", singleJsonObject("value", "刘金亮"));//联系人
        jsonObject.put("phone_number4", singleJsonObject("value", "18702156119"));//联系电话
        jsonObject.put("thing8", singleJsonObject("value", "商户已接单"));//温馨提示
        AppConfig oneAppConfig = appConfigMapperService.lambdaQuery().eq(AppConfig::getAppId, byIdSaleOrder.getAppId()).one();
        return subscribeMessageSend(one.getTemplateId(),
                "pages/order-list/order-list?sts=2",
                byIdUser.getOpenid(),
                jsonObject,
                oneAppConfig.getAppId(),
                wxVersion);
    }

    /**
     * 订单配送消息
     *
     * @param deliverOrderId
     * @return
     */
    public String sendOrderDeliverMsg(Long deliverOrderId,String wxVersion) {
        DeliveryOrder byIdDeliveryOrder = deliveryOrderMapperService.getById(deliverOrderId);
        Order byIdSaleOrder = orderMapperService.getById(byIdDeliveryOrder.getOrderId());
        MsgTemp oneMsgTemp = msgTempMapperService.lambdaQuery()
                .eq(MsgTemp::getAppId, byIdSaleOrder.getAppId())
                .eq(MsgTemp::getTemplateType, MgsTempEnum.confirm_order.getValue())
                .one();
        User byIdUser = userMapperService.getById(byIdSaleOrder.getUserId());
        //发送预约通知
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("character_string6", singleJsonObject("value", byIdSaleOrder.getOrderNum()));//订单编号
        jsonObject.put("phrase2", singleJsonObject("value", "labelByValue"));//订单状态
        jsonObject.put("phone_number11", singleJsonObject("value", "18702156118"));//骑手手机号

        String deliveryAddress = byIdDeliveryOrder.getDeliveryAddress();
        if (deliveryAddress.length() > 20) {//20个字符的限制
            deliveryAddress = "***" + deliveryAddress.substring(deliveryAddress.length() - 17);
        }
        jsonObject.put("thing12", singleJsonObject("value", deliveryAddress));//配送地址
        AppConfig oneAppConfig = appConfigMapperService.lambdaQuery().eq(AppConfig::getAppId, byIdSaleOrder.getAppId()).one();
        return subscribeMessageSend(oneMsgTemp.getTemplateId(),
                "pages/order-list/order-list?sts=3",
                byIdUser.getOpenid(),
                jsonObject,
                oneAppConfig.getAppId(),
                wxVersion);
    }

    public String subscribeMessageSend(String templateId, String page, String openid, JSONObject data,String appId,String wxVersion) {
        JSONObject request = new JSONObject();
        request.put("touser", openid);
        request.put("template_id", templateId);
        if (StringUtils.hasLength(page)) {
            request.put("page", page);
        }
        request.put("miniprogram_state", wxVersion);
        request.put("lang", "zh_CN");
        request.put("data", data);
        //获取token
        log.info("pre subscribeSend request ={}", request);
        AccessToken accessToken = accessTokenMapperService.getAccessToken(appId);
        ResponseEntity<String> stringResponseEntity = wxRestTemplate.postForEntity(String.format(messageSubscribeApi, accessToken.getAccessToken()),
                request.toString(), String.class);
        if (HttpStatus.OK.equals(stringResponseEntity.getStatusCode())) {
            log.info("subscribeSend successful ={}", stringResponseEntity.getBody());
        } else {
            log.error("订阅消息发送失败", stringResponseEntity.getBody());
            throw new MyRuntimeException("5002", "订阅消息发送失败");
        }
        return stringResponseEntity.getBody();
    }

    private JSONObject singleJsonObject(String key, String value) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(key, value);
        return jsonObject;
    }
}
